<?
require_once('./lib/authentication.lib.php');
require_once('./lib/sort.lib.php');
require_once('./lib/navigation.lib.php');
require_once('./lib/game.lib.php');
require_once('./lib/graph.lib.php');

if (isset($_GET["champ"]))
{
	$champ_id = mysql_escape_string($_GET["champ"]);

	$query = "SELECT * FROM Championship WHERE id = '$champ_id';";
	$result_champ = mysql_query($query);
	if (mysql_numrows($result_champ) != 1)
	{
		die("Invalid champ");
	}

	$champ_name = mysql_result($result_champ, 0, "name");
	$champ_begin = mysql_result($result_champ, 0, "begin");
	$champ_end = mysql_result($result_champ, 0, "end");

	$champ_begin = substr($champ_begin, 0, 4);
	$champ_end = substr($champ_end, 0, 4);
	?>
	<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
	        "http://www.w3.org/TR/REC-html40/loose.dtd">
	<HTML>
	<?
	echo "<HEAD><TITLE>$champ_name $champ_begin" . (($champ_begin !== $champ_end) ? "/$champ_end" : "") . "</TITLE>\n";
	?>
	<SCRIPT TYPE="text/javascript" SRC="js/game.js"></SCRIPT>
	<SCRIPT TYPE="text/javascript" SRC="js/game_squad.js"></SCRIPT>
	<SCRIPT TYPE="text/javascript" SRC="js/game_info.js"></SCRIPT>
	<SCRIPT TYPE="text/javascript" SRC="js/sorttable.js"></SCRIPT>
	<SCRIPT TYPE="text/javascript" SRC="js/tabs.js"></SCRIPT>
	<link rel="stylesheet" href="css/style.css" type="text/css">
	<link rel="stylesheet" href="css/squad.css" type="text/css">
	<STYLE type="text/css">
	div.tab_page
	{
	/* overflow: auto;
	height: 50%; */
	width: 700px;
	border: 1px solid #666;
	background-color: #ccc; 
	}

.game_inline_date
	{
	width: 15%;
	}
	.game_score
	{
	width: 100%;
	padding: 0px;
	border-spacing: 0px;
	}
	.game_info
	{
	width: 100%;
	}
	.game_inline_date
	{
	vertical-align: top;
	}
	table.form td
	{
	width: 15px;
	text-align: center;
	}
	table.attendance td
	{
	width: 50%;
	}
	</STYLE>
	</HEAD>
	<BODY>

	<? echo foot_header($champ_id, "team"); ?>

	<FORM action="javascript:void(0)">
	<SELECT onChange="javascript:window.location = this.options[this.selectedIndex].value">
	<?
	
	$query = "SELECT Team.id, Team.name FROM Team, team_group, `Group`, Phase WHERE Team.id = team_group.team AND team_group.group = `Group`.id AND `Group`.phase = Phase.id AND Phase.championship = '$champ_id' GROUP BY Team.id ORDER BY Team.name;";
	$result_team = mysql_query($query);
	$num_team = mysql_numrows($result_team);

	for ($i = 0; $i < $num_team; $i++)
	{
		$team_curr_id = mysql_result($result_team, $i, "Team.id");
		$team_name = mysql_result($result_team, $i, "Team.name");

		if ($i == 0)
		{
			$team_id = isset($_GET["team"]) ? mysql_escape_string($_GET["team"]) : $team_curr_id;
		}

		$selected = $team_curr_id == $team_id ? "selected" : "";
		echo "<OPTION $selected value='team.php?champ=$champ_id&team=$team_curr_id'>$team_name</OPTION>\n";
	}
	?>
	</SELECT>
	</FORM>

	<?
	$query = "SELECT Team.id, Team.name, Team.country, Team.logo FROM Team WHERE id = '$team_id';";
	$result_team = mysql_query($query);
	$num_team = mysql_numrows($result_team);
	$team_name = mysql_result($result_team, 0, "Team.name");
	$team_country = mysql_result($result_team, 0, "Team.country");
	$team_logo = mysql_result($result_team, 0, "Team.logo");

	echo "<H1>";
	if ($team_logo)
	{
		$team_logo = preg_replace("/\.svg/", "_100.png", $team_logo);
		echo "<IMG SRC='img/logos/$team_logo'>";
	}
	echo "$team_name - $team_country</H1>\n";
	
	?>
	
	<DIV class='tab_container' ID='tab_stats'>

	<?
	echo "<DIV ID='Results' class='tab_page'>\n";

	echo "<table class='sortable' id='games_table'>\n";
	echo "<tr class='table_head'><th>Date</th><th>Game</th><th></th><th></th></tr>\n";

	$game_ids = "''";
	$last_results = array();
	$query = "SELECT * FROM Phase WHERE championship = '$champ_id' ORDER BY `order`;";
	$result_phase = mysql_query($query);
	$num_phase = mysql_numrows($result_phase);
	for ($i = 0; $i < $num_phase; $i++)
	{
		$phase_id = mysql_result($result_phase, $i, "id");
		$phase_name = mysql_result($result_phase, $i, "name");

		$query = "SELECT Game.id game_id, Game.home, Game.away, Game.phase, Game.home_score, Game.away_score, Game.home_pen, Game.away_pen, Game.attendance, Game.date, Game.round, Game.played, Referee.name referee_name, Referee.location referee_location, Stadium.name stadium_name, Home.name home_name, Home.logo home_logo, Away.name away_name, Away.logo away_logo FROM Game LEFT JOIn Team as Home ON Game.home = Home.id LEFT JOIN Team as Away ON Game.away = Away.id LEFT JOIN Referee ON Game.referee = Referee.id LEFT JOIN Stadium ON Game.stadium = Stadium.id WHERE `phase` = $phase_id AND (Game.home = $team_id OR Game.away = $team_id) AND Game.played = 'played' ORDER BY Game.date ASC;";
		$result_game = mysql_query($query);

		while ($row = mysql_fetch_assoc($result_game))
		{
			$game_id = $row["game_id"];
			$home_team = $row["home"];
			$away_team = $row["away"];
			$home_score = $row["home_score"];
			$away_score = $row["away_score"];
			$home_pen = $row["home_pen"];
			$away_pen = $row["away_pen"];
			$home_name = $row["home_name"];
			$away_name = $row["away_name"];
			$attendance = $row["attendance"];
			$date = $row["date"];
			$round = $row["round"];
			$played = $row["played"];
			$stadium = $row["stadium_name"];
			$referee = $row["referee_name"];
			$referee_location = $row["referee_location"];

			$game_ids .= ", '$game_id'";

			$last_results[] = array("home" => $row["home"], "away" => $row["away"], "home_name" => $row["home_name"], "away_name" => $row["away_name"], "home_score" => $row["home_score"], "away_score" => $row["away_score"]);

			if ($home_team == $team_id)
			{
				$home_goals += $home_score;
				$home_against += $away_score;

				if ($attendance)
				{
				if ($attendance > $attend["max"])
				{
					$attend["max"] = $attendance;
					$attend["max_name"] = $away_name;
				}
				if (!isset($attend["min"]) or $attendance < $attend["min"])
				{
					$attend["min"] = $attendance;
					$attend["min_name"] = $away_name;
				}
				$attend["total"] += $attendance;
				$attend["count"] += 1;
				}

				$row["home_name"] = "<b>".$row["home_name"]."</b>";
			}
			else
			{
				$away_goals += $away_score;
				$away_against += $home_score;

				$row["away_name"] = "<b>".$row["away_name"]."</b>";
			}

			$date_str = date("d/m/Y", strtotime($date));

			echo "<tr>\n";
			echo "<td class='game_inline_date'>$date_str</td>\n";
			echo "<td class='game_score'>\n";
			echo write_game_score($row);

			echo "<DIV class='game_info'>\n";
#			echo write_game_info($row, $team_id, &$players_info);
			echo "</div>\n";
			echo "</td>\n";

			echo "<td class='show_info'><span onClick='writeInfo($game_id, this.parentNode.parentNode, this);'>Info</span></td>\n";
			echo "<td class='edit'><a href='javascript:edit_game($champ_id, $game_id);'>Edit</a></td>\n";
			echo "</tr>\n";
		}
	}
	echo "</TABLE>\n";
	echo "</DIV>\n";

	$game_ids .= "";

	echo "<DIV ID='Fixtures' class='tab_page'>\n";
	echo "<table class='sortable' id='games_table'>\n";
	echo "<tr class='table_head'><th>Date</th><th>Game</th><th></th><th></th></tr>\n";
	$query = "SELECT * FROM Phase WHERE championship = '$champ_id' ORDER BY `order`;";
	$result_phase = mysql_query($query);
	$num_phase = mysql_numrows($result_phase);
	for ($i = 0; $i < $num_phase; $i++)
	{
		$phase_id = mysql_result($result_phase, $i, "id");
		$phase_name = mysql_result($result_phase, $i, "name");

		$query = "SELECT Game.id game_id, Game.home, Game.away, Game.phase, Game.home_score, Game.away_score, Game.home_pen, Game.away_pen, Game.attendance, Game.date, Game.round, Game.played, Referee.name referee_name, Referee.location referee_location, Stadium.name stadium_name, Home.name home_name, Home.logo home_logo, Away.name away_name, Away.logo away_logo FROM Game LEFT JOIn Team as Home ON Game.home = Home.id LEFT JOIN Team as Away ON Game.away = Away.id LEFT JOIN Referee ON Game.referee = Referee.id LEFT JOIN Stadium ON Game.stadium = Stadium.id WHERE `phase` = $phase_id AND (Game.home = $team_id OR Game.away = $team_id) AND Game.played != 'played' ORDER BY Game.date ASC;";
		$result_game = mysql_query($query);

		while ($row = mysql_fetch_assoc($result_game))
		{
			$game_id = $row["game_id"];
			$home_team = $row["home"];
			$away_team = $row["away"];
			$home_score = $row["home_score"];
			$away_score = $row["away_score"];
			$home_pen = $row["home_pen"];
			$away_pen = $row["away_pen"];
			$home_name = $row["home_name"];
			$away_name = $row["away_name"];
			$attendance = $row["attendance"];
			$date = $row["date"];
			$round = $row["round"];
			$played = $row["played"];
			$stadium = $row["stadium_name"];
			$referee = $row["referee_name"];
			$referee_location = $row["referee_location"];

			$date_str = date("d/m/Y", strtotime($date));

			if ($home_team == $team_id)
			{
				$row["home_name"] = "<b>".$row["home_name"]."</b>";
			}
			else
			{
				$row["away_name"] = "<b>".$row["away_name"]."</b>";
			}

			echo "<tr>\n";
			echo "<td class='game_inline_date'>$date_str</td>\n";
			echo "<td class='game_score'>\n";
			echo write_game_score($row);

			echo "<DIV class='game_info'>\n";
#			echo write_game_info($row);
			echo "</div>\n";
			echo "</td>\n";

			echo "<td class='show_info'><span onClick='writeInfo($game_id, this.parentNode.parentNode, this);'>Info</span></td>\n";
			echo "<td class='edit'><a href='javascript:edit_game($champ_id, $game_id);'>Edit</a></td>\n";
			echo "</tr>\n";
		}
	}
	echo "</table>\n";
	echo "</DIV>\n";

	$query = "SELECT * from Goal WHERE game IN ($game_ids) AND team = $team_id;";
	$result_goal = mysql_query($query);
	while ($row = mysql_fetch_assoc($result_goal))
	{
		if ($row["own_goal"]) $players_info[$row["player"]]["own"]++;
		else $players_info[$row["player"]]["goals"]++;

		if ($row["penalty"]) $players_info[$row["player"]]["pen"]++;
	}

	echo "<DIV ID='Players' class='tab_page'>\n";
	$query = "SELECT Player.name, Player.id, Player.position FROM Player, team_player WHERE team_player.player = Player.id AND team_player.team = '$team_id' AND team_player.champ = '$champ_id';";
	$result_player = mysql_query($query);
	$num_player = mysql_numrows($result_player);
	$players = array();
	for ($i = 0; $i < $num_player; $i++)
	{
		$player_id = mysql_result($result_player, $i, "Player.id");
		$player_name = mysql_result($result_player, $i, "Player.name");
		$player_position = mysql_result($result_player, $i, "Player.position");

		$query = "SELECT player_game.team team, player_game.`on` `on`, player_game.off off, player_game.yellow yellow, player_game.red red, Game.id game_id, Game.home home, Game.home_score home_score, Game.away away, Game.away_score away_score FROM player_game JOIN Game ON Game.id = player_game.game JOIN Phase ON Phase.id = Game.phase JOIN Championship ON Phase.championship = Championship.id AND Championship.id = $champ_id WHERE player_game.player = $player_id;";
		$result_squad = mysql_query($query);
		while ($row = mysql_fetch_assoc($result_squad))
		{
			$players_info[$player_id]["apps"] += 0;
			$players_info[$player_id]["bench"] += 0;
			$players_info[$player_id]["sub"] += 0;

			if ($row["on"])
				$players_info[$player_id]["sub"]++;
			else if ($row["off"])
				$players_info[$player_id]["apps"]++;
			else
				$players_info[$player_id]["bench"]++;
			if ($row["yellow"])
				$players_info[$player_id]["yellow"] += $row["yellow"];
			if ($row["red"])
				$players_info[$player_id]["red"]++;
			if ($player_position == 'g')
			{
				if ($row["home"] == $row["team"])
				{
					$query = "SELECT id, time, team, own_goal FROM Goal WHERE game = '".$row["game_id"]."';";
					$result_goal = mysql_query($query);
					while ($row_goal = mysql_fetch_assoc($result_goal))
					{
						if (($row_goal["team"] == $row["away"] and $row_goal["own_goal"] == 0) or ($row_goal["team"] == $row["home"] and $row_goal["own_goal"] == 1))
							if ($row_goal["time"] > $row["on"] and ($row_goal["time"] < $row["off"] or $row["off"] == 90))
								$players_info[$player_id]["goals_against"]++;
					}
				}
				else if ($row["away"] == $row["team"])
				{
					$query = "SELECT id, time, team, own_goal FROM Goal WHERE game = '".$row["game_id"]."';";
					$result_goal = mysql_query($query);
					while ($row_goal = mysql_fetch_assoc($result_goal))
					{
						if (($row_goal["team"] == $row["home"] and $row_goal["own_goal"] == 0) or ($row_goal["team"] == $row["away"] and $row_goal["own_goal"] == 1))
							if ($row_goal["time"] > $row["on"] and ($row_goal["time"] < $row["off"] or $row["off"] == 90))
								$players_info[$player_id]["goals_against"]++;
					}
				}

			}
		}

		if (!isset($players_info[$player_id]["goals"])) $players_info[$player_id]["goals"] = 0;
		if (!isset($players_info[$player_id]["pen"])) $players_info[$player_id]["pen"] = 0;
		if (!isset($players_info[$player_id]["own"])) $players_info[$player_id]["own"] = 0;
		if (!isset($players_info[$player_id]["yellow"])) $players_info[$player_id]["yellow"] = 0;
		if (!isset($players_info[$player_id]["red"])) $players_info[$player_id]["red"] = 0;
		
		$players[] = array("id" => $player_id, "name" => $player_name, "position" => $player_position, "goals" => $players_info[$player_id]["goals"], "pens" => $players_info[$player_id]["pen"], "own" => $players_info[$player_id]["own"], "apps" => $players_info[$player_id]["apps"], "sub" => $players_info[$player_id]["sub"], "bench" => $players_info[$player_id]["bench"], "yellow" => $players_info[$player_id]["yellow"], "red" => $players_info[$player_id]["red"], "goals_against" => $players_info[$player_id]["goals_against"]);
	}

	$players = multi_sort($players, array(array("goals", false), array("name", true)));
	
	echo "<table class='sortable full' id='player_table'>\n";
	echo "<tr class='table_head'><th>Name</th><th>Position</th><th>Goals</th><th>Pens</th><th>O.Gs</th><th>Y</th><th>R</th><th>Start</th><th>Sub</th><th>Bench</th><th>Apps</th></tr>\n";

	$count = 0;
	while (list($key, $value) = each($players))
	{
		?>
		<tr class='table_line_<?if ($count++ % 2 == 0) { echo "even"; } else { echo "odd"; }?>'>
		<td align='left'><a href='player.php?champ=<?echo $champ_id?>&player=<?echo $players[$key]["id"]?>'><?echo $players[$key]["name"]?></a></td>
		<td align='right'><?echo $players[$key]["position"]?></td>
		<td align='right'><?
		echo $players[$key]["goals"];
		if ($players[$key]["goals_against"])
			echo " (-".$players[$key]["goals_against"].")";
		?></td>
		<td align='right'><?echo $players[$key]["pens"]?></td>
		<td align='right'><?echo $players[$key]["own"]?></td>
		<td align='right'><?echo $players[$key]["yellow"]?></td>
		<td align='right'><?echo $players[$key]["red"]?></td>
		<td align='right'><?echo $players[$key]["apps"]?></td>
		<td align='right'><?echo $players[$key]["sub"]?></td>
		<td align='right'><?echo $players[$key]["bench"]?></td>
		<td align='right'><?echo $players[$key]["apps"] + $players[$key]["sub"] + $players[$key]["bench"]?></td>
		</tr>
		<?
	}
	echo "</table>\n";
	echo "</DIV>\n";
?>
	<DIV id="Misc" class="tab_page">
	<table class="full attendance"><tr>
	<td>
	<table width="full">
	<caption>Attendances:</caption>
	<tbody>
	<tr><td>Max:</td><td align='right'><?echo number_format($attend["max"], 0, ",", ".")?></td><td><?echo $attend["max_name"]?></td></tr>
	<tr><td>Min:</td><td align='right'><?echo number_format($attend["min"], 0, ",", ".")?></td><td><?echo $attend["min_name"]?></td></tr>
	<tr><td>Avg:</td><td align='right'><?echo number_format($attend["total"]/($attend["count"] ? $attend["count"] : 1), 0, ",", ".")?></td><td></td></tr>
	<tr><td>Total:</td><td align='right'><?echo number_format($attend["total"], 0, ",", ".")?></td><td></td></tr>
	</tbody>
	</table>
	</td>
	<td>
	<table width="full">
	<caption>Goals:</caption>
	<tbody>
	<tr><th></th><th>For</th><th>Against</th></tr>
	<tr><td>Total:</td><td align='right'><?echo $home_goals + $away_goals?></td><td align='right'><?echo $home_against + $away_against?></td></tr>
	<tr><td>Home:</td><td align='right'><?echo $home_goals?></td><td align='right'><?echo $home_against?></td></tr>
	<tr><td>Away:</td><td align='right'><?echo $away_goals?></td><td align='right'><?echo $away_against?></td></tr>
	</tbody>
	</table>
	</td>
	</tr></table>
	</DIV>

	</DIV>

	<DIV id="form">
	<?
	echo "Home: <table class='form'><tr>\n";
	if (count($last_results) > 10) $i = count($last_results) - 10;
	else $i = 0;
	for (; $i < count($last_results); $i++)
	{
		if ($last_results[$i]["home"] == $team_id)
		{
			echo "<td title='header=[] body=[" . $last_results[$i]["home_name"] . " " . $last_results[$i]["home_score"] . " x " . $last_results[$i]["away_score"] . " " . $last_results[$i]["away_name"] . "]' ";
			if ($last_results[$i]["home_score"] > $last_results[$i]["away_score"])
				echo "style='background-color: blue'>W</td>";
			else if ($last_results[$i]["home_score"] < $last_results[$i]["away_score"])
				echo "style='background-color: red'>L</td>";
			else
				echo "style='background-color: lightgray'>D</td>";
		}
	}
	echo "</tr></table>\n";
	echo "Away: <table class='form'><tr>\n";
	if (count($last_results) > 10) $i = count($last_results) - 10;
	else $i = 0;
	for (; $i < count($last_results); $i++)
	{
		if ($last_results[$i]["away"] == $team_id)
		{
			echo "<td title='header=[] body=[" . $last_results[$i]["home_name"] . " " . $last_results[$i]["home_score"] . " x " . $last_results[$i]["away_score"] . " " . $last_results[$i]["away_name"] . "]' ";
			if ($last_results[$i]["home_score"] < $last_results[$i]["away_score"])
				echo "style='background-color: blue'>W</td>";
			else if ($last_results[$i]["home_score"] > $last_results[$i]["away_score"])
				echo "style='background-color: red'>L</td>";
			else
				echo "style='background-color: lightgray'>D</td>";
		}
	}
	echo "</tr></table>\n";
	?>
	</DIV>

	<?
	echo get_graph($champ_id, $team_id);
	?>

	<? echo foot_footer($champ_id, "team"); ?>

	<SCRIPT TYPE="text/javascript" SRC="js/boxOver.js"></SCRIPT>
</BODY>
</HTML>
<?
}
?>
